import os

from utils import date_util, k_util, ave_util, excel_util, json_util, form_util, doc_util, macd_util, boll_util, \
    read_config

today_str = date_util.get_format_date_str("%Y-%m-%d")
result_path = os.path.join(read_config.data_path, 'result', '突破均线', today_str, '历史验证')
result_file_name = '验证结果'
view_file_path = os.path.join(result_path, '验证')

base_result_path = os.path.join(read_config.data_path, 'result', '均线形态', today_str)
document_path = os.path.join(read_config.data_path, 'service', 'document')
if not os.path.exists(view_file_path):
    os.makedirs(view_file_path)  # 没有创建文件夹

time_count = 0
list_stock = []
up_fd = 1  # 突破幅度百分比 * 10000
down_fd = 1  # 突破幅度百分比 * 10000
compare_size = 10
score_line = 0.8
result_dict = {}


def monitor_up_down(list_s, size):
    global list_stock
    list_stock = list_s
    for stock_info in list_stock:
        stock_info = json_util.info_to_json(stock_info)
        capital_pool = 100000  # 十万的金额
        position_money = 0
        hand_num = 0
        code = stock_info['code']
        name = stock_info['name']
        content_arr = [['编码', '名称', '日期', '成交价', '买卖', '持有股', '变更资金', '总资本', '间隔天数', 'macd', 'boll', 'k_form']]
        k_lines = k_util.day_k_local(code, size + 5)  # k线
        k_lines.reverse()
        size = len(k_lines)
        k_lines_n = k_lines[0:5]
        pointer = 0  # k_lines_n的替换指针
        ave_price = ave_util.ave_line_price(k_lines_n, 5)
        sp4 = float(json_util.info_to_json(k_lines_n[4])['sp'])
        up_down_flag = 0  # 0:需要突破 1:监控跌破
        if sp4 > ave_price: up_down_flag = 1
        for num in range(size - 5):
            ave_price = ave_util.ave_line_price(k_lines_n, 5)
            pointer_v1 = pointer + 4  # k_lines_n 上一天的参数
            if pointer_v1 > 4:
                pointer_v1 = pointer_v1 - 5
            spp = float(json_util.info_to_json(k_lines_n[pointer_v1])['sp'])  # 上一天的收盘价
            kf5 = json_util.info_to_json(k_lines[num + 5])  # 最新一天k
            k_lines_n[pointer] = kf5
            if pointer == 4:
                pointer = 0
            else:
                pointer += 1
            max5 = float(kf5['max'])
            min5 = float(kf5['min'])
            kp5 = float(kf5['kp'])
            rq5 = kf5['rq']
            sp5 = float(kf5['sp'])
            if up_down_flag == 0:  # 0:需要突破5日均线
                # 有效突破五日均线 准备买入
                if (max5 - ave_price) / spp * 10000 > up_fd:
                    # 增加 形态 判断
                    # 增加 macd 形态判断
                    # 增加 boll 形态判断
                    macd_form = macd_util.macd_form(macd_util.get_macd_interval(code, rq5, 3))
                    boll_form = boll_util.judge_form(boll_util.get_boll_interval(code, rq5, 3), sp5)
                    if num >= compare_size - 6:
                        x = form_util.gen_x(k_lines[num - compare_size + 6:num - compare_size + 16], 'sp')
                        k_form = form_util.get_highest_score(form_util.exam_all_form(x))
                    else:
                        k_form = {'form': '', 'score': 0, 'front': 0, 'amplitude': 15}
                    if macd_form != 'v' and macd_form != '/':
                        continue
                    if k_form['score'] < score_line:
                        continue
                    # if k_form['form'] != 'L' \
                    #         and k_form['form'] != '厂' \
                    #         and k_form['form'] != 'n' \
                    #         and k_form['form'] != '\\':
                    #     continue
                    if k_form['form'] != '\\':
                        continue
                    # 空仓天数
                    interval_days = 0
                    length = len(content_arr)
                    if length != 1:
                        time_str = content_arr[length - 1][2]
                        interval_days = date_util.diff_days_str(time_str, rq5)
                    # 买入价格
                    buy_price = ave_price + ave_price * up_fd / 10000
                    if min5 > buy_price:
                        print(name + '当天' + rq5 + '高开高走')
                        buy_price = float(kp5)
                    hand_num = int((capital_pool - position_money) / buy_price / 100)
                    if hand_num == 0: continue
                    position_money = hand_num * buy_price * 100  # 持仓资金
                    capital_pool = capital_pool - position_money - position_money * 0.00025  # 总资产
                    up_down_flag = 1  # 变更flag
                    row_arr = [code, name, rq5, buy_price, 1, hand_num * 100, position_money,
                               capital_pool + position_money, interval_days, macd_form, boll_form, str(k_form)]
                    content_arr.append(row_arr)
            elif up_down_flag == 1:  # 1:需要突破5日均线
                if (ave_price - min5) / spp * 10000 > down_fd:
                    macd_form = macd_util.macd_form(macd_util.get_macd_interval(code, rq5, 3))
                    if macd_form != '\\' and macd_form != '^':
                        continue
                    # 持仓天数
                    interval_days = 0
                    length = len(content_arr)
                    if length != 1:
                        time_str = content_arr[length - 1][2]
                        interval_days = date_util.diff_days_str(time_str, rq5)
                    # 卖出价格
                    sell_price = ave_price - ave_price * down_fd / 10000
                    if sell_price > kp5:  # 当收盘价大于 当日最高价时
                        print(name + '当天' + rq5 + '暴跌以开盘价卖出')
                        sell_price = kp5
                    if hand_num == 0:
                        up_down_flag = 0
                        continue
                    position_money = hand_num * sell_price * 100  # 减仓资金
                    capital_pool = capital_pool + position_money - position_money * 0.00025
                    up_down_flag = 0  # 变更flag
                    row_arr = [code, name, rq5, sell_price, -1, 0, position_money, capital_pool, interval_days,
                               macd_form, '', '']
                    position_money = 0  # 重置参数
                    hand_num = 0  # 重置参数
                    content_arr.append(row_arr)
        if len(content_arr) > 1:
            excel_util.gen_an_excel(view_file_path, name + code, '', content_arr)


def monitor_all_indicators():
    print('开始监控')
    stock_list = doc_util.get_path_doc_info(os.path.join(document_path, '验证股票'))
    monitor_up_down(json_util.info_to_json(stock_list), 200)


if __name__ == '__main__':
    monitor_all_indicators()
